package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.PfOpenCityMapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzRebateShareMapper;
import com.stylefeng.guns.rest.common.persistence.dao.WzUserRebateMapper;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.persistence.dao.WzMapRebateMapper;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzFinanceService;
import com.stylefeng.guns.rest.modular.wz.controller.WzShareApi;
import com.stylefeng.guns.rest.modular.wz.service.IWzMapRebateService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import com.stylefeng.guns.rest.pay.method.PayMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 返利表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2019-03-17
 */
@Service
public class WzMapRebateServiceImpl extends ServiceImpl<WzMapRebateMapper, WzMapRebate> implements IWzMapRebateService {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzFinanceService financeService;
    @Autowired
    private WzRebateShareMapper rebateShareMapper;
    @Autowired
    private WzUserRebateMapper userRebateMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;

    /**
     * 创建返利活动
     */
    public Res createUserRebate(ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();//下单用户编号
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");
        int quantity = paramMap.getIntMisValid("quantity");//购买数量
        int amount = paramMap.getIntMisValid("amount");//前台计算价格
        int isRewardBalanceDeduction = paramMap.getIntMisValid("isRewardBalanceDeduction");//是否用积分余额抵扣：0-否;1-是
        int payMethod = paramMap.getIntMisValid("payMethod");//支付类型：1-支付宝;2-微信;
        WzUser user = cacheService.user(userCode);//用户信息
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);//返利活动

        //后台金额计算
        int realAmount = quantity * mapRebate.getRebatePrice();
        if(quantity > mapRebate.getLimitNumber()){
            return Res.fail("每单限购"+mapRebate.getLimitNumber()+"件!");
        }

        //现金支付
        if(isRewardBalanceDeduction == 0){
            if(amount != realAmount){
                return Res.fail("金额错误!");
            }
            //现金支付记录
            WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
            userFinanceRecord.setId(IdWorker.getId());
            userFinanceRecord.setPayMethod(payMethod);
            //创建返利活动
            WzUserRebate userRebate = new WzUserRebate();
            userRebate.setUserRebateId(IdWorker.getId());

            WzCoupon coupon = cacheService.coupon(mapRebate.getCouponId());//券信息
            if(coupon.getUseType() == EnWzCoupon.UserType_Delivery.getIndex()){
                String userInfoId = paramMap.getStrMisValid("userInfoId");
                userRebate.setUserInfoId(userInfoId);
            }
            paramMap.put("userRebateId",userRebate.getUserRebateId());
            //数据保存处理
            boolean r = financeService.createUserRebate(realAmount,quantity,mapRebate,user,userFinanceRecord,userRebate);
            if(r){
                //返回支付数据
                if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
                    String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-返利订单");
                    paramMap.put("alipay",str);
                    return Res.success(paramMap);
                }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
                    Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-返利订单","8.8.8.8");
                    paramMap.put("weixin",m);
                    return Res.success(paramMap);
                }
            }
        }
        return Res.fail();
    }

    public Res createRebate(ParamMap paramMap, WzUser user, WzMapRebate mapRebate, int payMethod, int quantity, int realAmount) throws Exception{
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();//现金支付记录
        userFinanceRecord.setId(IdWorker.getId());
        userFinanceRecord.setPayMethod(payMethod);
        //生成返利活动
        WzUserRebate userRebate = new WzUserRebate();
        userRebate.setUserRebateId(IdWorker.getId());
        userRebate.setCouponId(mapRebate.getCouponId());
        userRebate.setUserCode(user.getUserCode());
        userRebate.setBenefit(mapRebate.getBenefit());
        userRebate.setMerchantName(mapRebate.getMerchantName());
        userRebate.setPic(mapRebate.getPic());
        userRebate.setNickName(user.getNickName());
        String avatarUrl=user.getAvatarUrl();
        if(!avatarUrl.startsWith("http")){
            avatarUrl= Consts.DOMAIN+avatarUrl;
        }
        userRebate.setAvatarUrl(avatarUrl);
        userRebate.setQuantity(quantity);
        userRebate.setStatus(EnWzMapRebate.USERREBATE_STATUS_Wait_Pay.getIndex());
        userRebate.setPayTime(DateUtil.addMinute(new Date(),30));//30分钟内支付
        userRebate.setNeedShareNumber(mapRebate.getNeedShareNumber());
        userRebate.setPrice(mapRebate.getPrice());
        userRebate.setRebatePrice(mapRebate.getRebatePrice());
        userRebate.setCreateTime(new Date());
        userRebate.setMapRebateId(mapRebate.getMapRebateId());

        WzCoupon coupon = cacheService.coupon(mapRebate.getCouponId());//券信息
        if(coupon.getUseType() == EnWzCoupon.UserType_Delivery.getIndex()){
            String userInfoId = paramMap.getStrMisValid("userInfoId");
            userRebate.setUserInfoId(userInfoId);
        }

        paramMap.put("mapRebateId",mapRebate.getMapRebateId());
        //数据保存处理
        boolean r = financeService.createRebate(realAmount,userRebate,user,userFinanceRecord);
        if(r){
            //返回支付数据
            if(payMethod == EnWzUserFinanceRecord.payMethod_alipay.getIndex()){//支付宝支付
                String str = PayMethod.aliAppPay(userFinanceRecord.getId().toString(),realAmount,"外赚-返利订单");
                paramMap.put("alipay",str);
                return Res.success(paramMap);
            }else if(payMethod == EnWzUserFinanceRecord.payMethod_weixin.getIndex()){//微信支付
                Map m = PayMethod.wxAppPay(realAmount,userFinanceRecord.getId().toString(),"外赚-返利订单","8.8.8.8");
                paramMap.put("weixin",m);
                return Res.success(paramMap);
            }
        }
        return Res.fail();
    }

    @Transactional
    public boolean rebateShareSave(WzRebateShare rebateShare, WzUserRebate userRebate) {
        int r = userRebateMapper.updateById(userRebate);
        if (r > 0) {
            r = rebateShareMapper.insert(rebateShare);
            if(r > 0) {
                return true;
            }
        }
        return false;
    }

    public String shareLinkId(WzAdvMap advMap, WzMapRebate mapRebate, WzCoupon coupon, int needShareNumber, int rebatePrice) throws Exception{
        String cityName=getCityNameByAdCode(advMap.getAdCode());
        String shareLink=advMap.getShareLink();
        String url= WzShareApi.getURLContent(shareLink);
        String rule="";
        if(coupon.getRuleType()==1){
            rule=coupon.getRule().replace("\n","<br/>").replace(" ","&nbsp;");
        }else{
            rule="<img src='"+coupon.getRule()+"'width='100%'>";
        }
        String rebate="<link rel='stylesheet' href='http://oss.50waizhuan.com/wzAdvMap.css' type='text/css' />"+
                "<script src=\"http://oss.50waizhuan.com/wzAdvMap.js\"></script>\n"+
                "<script>\n" +
                "    var rebate= \"<img src='"+mapRebate.getPic()+"' width='100%'>\\n\" +\n" +
                "            \"            <div style='margin:10pt 10pt 10pt 10pt;' >\\n\" +\n" +
                "            \"                <span style=\\\"font-size:9pt\\\">原价<span style=\\\"font-weight:bold\\\">￥"+Double.parseDouble(coupon.getPrice().toString())/100+"</span> &nbsp "+needShareNumber+"人助力<span style='color:#E51C23'>立返￥</span><span style='color:#E51C23;font-size: 12pt;font-weight:bold' >"+Double.parseDouble((coupon.getPrice()-rebatePrice)+"")/100+"</span>/件</span>\\n\" +\n" +
                "            \"                <span style='color:#878787;font-size: 10pt;float: right;margin-top: 2pt;'>限"+cityName+"</span>\\n\" +\n" +
                "            \"        </div >\\n\" +\n" +
                "            \"            <div style=\\\"margin:10pt 10pt 10pt 10pt;font-weight: bold;color: #101010;font-size: 14px;\\\">\\n\" +\n" +
                "            \"                【"+coupon.getMerchantName()+"】 "+coupon.getBenefit()+"\\n\" +\n" +
                "            \"        </div>\\n\" +\n" +
                "            \"       <div style=\\\"margin:0pt 0pt 10pt 10pt;color: #878787;font-size: 12px;\\\"> 礼券有效期:&nbsp;&nbsp;"+DateUtil.toString(coupon.getBeginTime(),new SimpleDateFormat("yyyy.MM.dd"))+"  - "+DateUtil.toString(coupon.getEndTime(),new SimpleDateFormat("yyyy.MM.dd"))+"</div>\\n\" +\n" +
                "            \"            <div style=\\\"height:5pt;background:#F6F6F6\\\"></div>\\n\" +\n" +
                "            \"            <div class='detail'>礼券规则</div>\\n\" +\n" +
                "            \"            <div style=\\\"margin:10pt 10pt 10pt 10pt;color: #101010;font-size: 12px;\\\">\\n\" +\n" +
                "            \"                "+rule+"\\n\" +\n" +
                "            \"        </div>\\n\" +\n" +
                "            \"            <div style=\\\"height:5pt;background:#F6F6F6\\\"></div>\";\n" +
                "        $('#headBanner').append(rebate);\n" +
                "        $('#advMapHead').css('display','none');\n" +
                "        $('#advMapFoot').css('display','none');\n" +
                "</script>";
        Long id= IdWorker.getId();
        AliOssUtil.putStream(new ByteArrayInputStream((url+rebate).getBytes()), id+".html", 5);
        PfFile file = new PfFile();
        file.setName(mapRebate.getMerchantName()+"_返利活动");
        file.setType(EnPfFile.TYPE_Website.getIndex());
        file.setFileUrl(id + ".html");
        file.setStatus(EnPfFile.Status_Used.getIndex());
        file.setBucketName(Consts.bucketName_share);
        file.setCreateTime(new Date());
        file.insert();
        return id.toString();
    }

    public String getCityNameByAdCode(String adCode) {
        String str = "";
        String[] adCodes=adCode.split(",");
        if(adCodes.length <= 0){
            return "金坛区";
        }
        for(String a:adCodes){
            List<PfOpenCity> openCities = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("ad_code",a));
            if(openCities.size() > 0){
                str += openCities.get(0).getName() + " ";
            }
        }
        return str.substring(0,str.length()-1);
    }
}
